package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.jetcache.utils.JetCacheUtils;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.util.TreeUtil;
import com.bifang.module.base.common.vo.org.OrgTreeVO;
import com.bifang.module.base.common.vo.tree.TreeRetVO;
import com.bifang.module.base.common.vo.tree.TreeVO;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.system.common.enums.ArticleStatusEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.enums.EduFormEnrollParamsDictEnum;
import com.jwsoft.manager.common.enums.EduFormTypeEnum;
import com.jwsoft.manager.common.enums.SchoolCategoryEnum;
import com.jwsoft.manager.common.enums.SchoolConfigDictEnum;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.eduFormEnroll.EduFormEnrollKeyVO;
import com.jwsoft.manager.common.vo.eduFormEnroll.EduFormEnrollQueryVO;
import com.jwsoft.manager.common.vo.eduFormEnroll.EduFormEnrollSchoolVO;
import com.jwsoft.manager.common.vo.eduFormEnroll.EduFormEnrollVO;
import com.jwsoft.manager.common.vo.eduFormEnrollParams.EduFormEnrollParamsVO;
import com.jwsoft.manager.common.vo.eduFormEnrollParams.SaveFormEnrollParamsVO;
import com.jwsoft.manager.common.vo.eduFormSpecial.FormSaveVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduFormEnrollIntegration;
import com.jwsoft.manager.core.integration.OperationCacheIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 报名表单管理业务实现类
 *
 * @author chenzh
 * @since 2023-02-10
 */
@ApiService(funcCode = "eduFormEnroll", title = "报名表单管理")
public class EduFormEnrollIntegrationImpl implements EduFormEnrollIntegration {

    @Autowired
    public EduFormEnrollService eduFormEnrollService;
    @Autowired
    public EduFormEnrollParamsService eduFormEnrollParamsService;
    @Autowired
    private DictHelper dictHelper;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    private OperationCacheIntegration operationCacheIntegration;
    @Autowired
    private EduAppointSchoolService eduAppointSchoolService;
    @Autowired
    private EduStudentEnrollService eduStudentEnrollService;
    @Autowired
    private EduSchoolService eduSchoolService;
    @Autowired
    private EduStudentEnrollKindergartenService eduStudentEnrollKindergartenService;


    @Override
    @OpApi(funcCode = "eduFormEnroll0001", title = "报名表单管理分页查询",
            funcType = FuncTypeEnum.query ,publicFlag = BoolEnum.TRUE,checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduFormEnrollVO> getList(EduFormEnrollQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        QueryWrapper<EduFormEnroll> formQueryWrapper = new QueryWrapper<>();
        if(ObjectUtils.isEmpty(vo.getYear())) {
            int year;
            EduOperationCacheDetailVO cacheDetailVO = operationCacheIntegration.getPeriodYear();

            if (cacheDetailVO != null) {
                year = cacheDetailVO.getYear();
            } else {
                year = DateUtil.thisYear();
            }
            vo.setYear(year);
        }
        formQueryWrapper
                .lambda()
                .eq(!ObjectUtils.isEmpty(vo.getYear()), EduFormEnroll::getYear, vo.getYear())
                .eq(
                        !ObjectUtils.isEmpty(vo.getFormRefName()),
                        EduFormEnroll::getFormRefName,
                        vo.getFormRefName())
                .eq(
                        !ObjectUtils.isEmpty(vo.getFormRefId()),
                        EduFormEnroll::getFormRefId,
                        vo.getFormRefId())
                .eq(EduFormEnroll::getSchoolId, vo.getSchoolId())
                .eq(!ObjectUtils.isEmpty(vo.getConfigType()),EduFormEnroll::getConfigType,vo.getConfigType())
                .orderByAsc(EduFormEnroll::getOrderNo);
        List<EduFormEnroll> list = eduFormEnrollService.list(formQueryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduFormEnroll> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduFormEnrollVO> resultList = Convert.toList(EduFormEnrollVO.class, pageInfo.getList());
        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(SchoolConfigDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduFormEnroll0002", title = "报名表单管理根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduFormEnrollVO getById(EduFormEnrollKeyVO vo) {
        EduFormEnroll entity = eduFormEnrollService.getById(vo.getFormId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduFormEnrollVO result = Convert.convert(EduFormEnrollVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduFormEnroll0003", title = "报名表单管理保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduFormEnrollVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
        EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(vo.getSchoolId());
        //判断是否存在报名数据
        if (SchoolCategoryEnum.KINDERGARTEN.getType().equalsIgnoreCase(eduSchoolVO.getSchoolCategory())) {
            //幼儿园允许新增招生类别和修改没有报名数据的招生类别
            String configName = "";
            if(StringUtils.isBlank(vo.getFormId())){
                configName = vo.getConfigName();
            }else {
                EduFormEnroll eduFormEnroll = eduFormEnrollService.getById(vo.getFormId());
                if(eduFormEnroll != null){
                    configName = eduFormEnroll.getConfigName();
                }
            }
            QueryWrapper<EduStudentEnrollKindergarten> wshQuery = new QueryWrapper<>();
            wshQuery.lambda().eq(EduStudentEnrollKindergarten::getSchoolId, vo.getSchoolId())
                    .eq(EduStudentEnrollKindergarten::getConfigName,configName)
                    .eq(EduStudentEnrollKindergarten::getConfigType,vo.getConfigType())
                    .eq(EduStudentEnrollKindergarten::getYear, vo.getYear());
            long enrollCount = eduStudentEnrollKindergartenService.count(wshQuery);
            if (enrollCount > 0) {
                throw new AppException("该招生类别存在报名数据，不允许修改招生方案");
            }
        } else {
            // QueryWrapper<EduStudentEnroll> wshQuery = new QueryWrapper<>();
            // wshQuery.lambda().eq(EduStudentEnroll::getSchoolId, vo.getSchoolId())
            //         .eq(EduStudentEnroll::getYear, vo.getYear());
            // long enrollCount = eduStudentEnrollService.count(wshQuery);
            // if (enrollCount > 0) {
            //     throw new AppException("存在报名数据，不允许修改招生方案");
            // }
        }
    }

    @Override
    @OpApi(funcCode = "eduFormEnroll0004", title = "报名表单管理新增/修改", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduFormEnroll0004",
            operationName = "报名表单管理新增/修改",
            dataType = "formId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduFormEnrollVO save(EduFormEnrollVO vo) {
        //保存前校验

        if(vo.getYear()==null){
            Integer year = eduHelper.thisYear();;
            vo.setYear(year);
        }
        if(StringUtils.isBlank(vo.getValidStatus())){
            throw new AppException("有效状态不能为空");
        }   

        if(StringUtils.isBlank(vo.getFormName())){
            throw new AppException("标题不能为空");
        }
        if(ObjectUtils.isEmpty(vo.getSchoolId())){
            throw new AppException("学校Id不能为空");
        }
        EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(vo.getSchoolId());

        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(eduSchoolVO.getAreaCode());
        }
        if(StringUtils.isBlank(vo.getAreaCode())){
            throw new AppException("行政区划不能为空");
        }

        if(StringUtils.isBlank(vo.getConfigType())&&SchoolCategoryEnum.KINDERGARTEN.getType().equalsIgnoreCase(eduSchoolVO.getSchoolCategory())){
            throw new AppException("学段不能为空");
        }
        //限制幼儿园招生类别不能为空
        if(StringUtils.isBlank(vo.getConfigName())&&SchoolCategoryEnum.KINDERGARTEN.getType().equalsIgnoreCase(eduSchoolVO.getSchoolCategory())){
            throw new AppException("招生类别不能为空");
        }

        if(ObjectUtils.isEmpty(vo.getOrderNo())){
            throw new AppException("排序字段不能为空");
        }

        checkSave(vo);
        EduFormEnroll form = Convert.convert(EduFormEnroll.class,vo);
        String orgId = eduSchoolVO.getOrgId();
        if (ObjectUtils.isEmpty(form.getFormId())) {
            QueryWrapper<EduFormEnroll> checkQueryWrapper = new QueryWrapper<>();
            checkQueryWrapper
                    .lambda()
                    .eq(EduFormEnroll::getSchoolId, orgId)
                    .eq(EduFormEnroll::getFormType, form.getFormType())
                    .eq(EduFormEnroll::getFormClass, form.getFormClass())
                    .eq(EduFormEnroll::getYear,vo.getYear());
            long count = eduFormEnrollService.count(checkQueryWrapper);
            if (count > 0) {
                throw new AppException("当前年度已有相同类型的表单，请前往修改");
            }
            form.setFormId(IdUtil.simpleUUID());
        }
        if (!ObjectUtils.isEmpty(form.getFormType())) {
            if (form.getFormType().equals(EduFormTypeEnum.NURSERYENROLL.getType())) {
                form.setSchoolId(orgId);
                form.setFormRefName("edu_enrollmen_brochure");
                form.setStatus(ArticleStatusEnum.draft.getType());
                form.setValidStatus(vo.getValidStatus());
                form.setYear(vo.getYear());
                QueryWrapper<EduFormEnroll> formQueryWrapper = new QueryWrapper<>();
                formQueryWrapper
                        .lambda()
                        .eq(EduFormEnroll::getSchoolId, orgId)
                        .eq(
                                !ObjectUtils.isEmpty(vo.getConfigName()),
                                EduFormEnroll::getConfigName,
                                vo.getConfigName())
                        .eq(EduFormEnroll::getConfigType, vo.getConfigType())
                        .eq(EduFormEnroll::getFormRefId, vo.getFormRefId())
                        .eq(EduFormEnroll::getFormRefName, "edu_enrollmen_brochure")
                        .ne(
                                !ObjectUtils.isEmpty(vo.getFormId()),
                                EduFormEnroll::getFormId,
                                vo.getFormId());

                long count = eduFormEnrollService.count(formQueryWrapper);
                if (count > 0) {
                    throw new AppException("当前学校已存在该招生类别，请输入其他招生类别");
                }
                QueryWrapper<EduFormEnroll> form2QueryWrapper = new QueryWrapper<>();
                form2QueryWrapper
                        .lambda()
                        .eq(EduFormEnroll::getSchoolId, orgId)
                        .eq(EduFormEnroll::getOrderNo, vo.getOrderNo())
                        .eq(EduFormEnroll::getFormRefId, vo.getFormRefId())
                        .eq(EduFormEnroll::getFormRefName, "edu_enrollmen_brochure")
                        .ne(
                                !ObjectUtils.isEmpty(vo.getFormId()),
                                EduFormEnroll::getFormId,
                                vo.getFormId());

                long count2 = eduFormEnrollService.count(form2QueryWrapper);
                if (count2 > 0) {
                    throw new AppException("当前学校已存在排序号，请输入其他排序号");
                }

                QueryWrapper<EduStudentEnrollKindergarten> detailQueryWrapper = new QueryWrapper<>();
                detailQueryWrapper.lambda().eq(EduStudentEnrollKindergarten::getFormId, vo.getFormId());

                long count3 = eduStudentEnrollKindergartenService.count(detailQueryWrapper);
                if (count3 > 0) {
                    throw new AppException("已存在申报数据，不允许修改");
                }

                form.setFormClass(vo.getFormClass());
                form.setConfigName(vo.getConfigName());
                form.setOrderNo(vo.getOrderNo());
                eduFormEnrollService.saveOrUpdate(form);
            }else if (form.getFormType().equals(EduFormTypeEnum.YWENROLL.getType())) {
                form.setSchoolId(orgId);
                form.setFormRefName("edu_enrollmen_brochure");
                form.setStatus(ArticleStatusEnum.draft.getType());
                form.setValidStatus(vo.getValidStatus());
                form.setYear(vo.getYear());
                if (!ObjectUtils.isEmpty(vo.getOrderNo()) && vo.getOrderNo() == 1
                        || vo.getOrderNo() == 2
                        || vo.getOrderNo() == 3
                        || vo.getOrderNo() == 4
                        || vo.getOrderNo() == 6
                        || vo.getOrderNo() == 97 //调剂
                        || vo.getOrderNo() == 98 //公办抢报
                        || vo.getOrderNo() == 99) { //学校线下录入
                    throw new AppException("当前排序号为A,B,C,特殊户口,E类和特殊通道类别专属排序号，不允许使用");
                }

                QueryWrapper<EduFormEnroll> formQueryWrapper = new QueryWrapper<>();
                formQueryWrapper
                        .lambda()
                        .eq(EduFormEnroll::getSchoolId, orgId)
                        .eq(
                                !ObjectUtils.isEmpty(vo.getConfigName()),
                                EduFormEnroll::getConfigName,
                                vo.getConfigName())
                        .eq(EduFormEnroll::getConfigType, vo.getConfigType())
                        .eq(EduFormEnroll::getFormRefId, vo.getFormRefId())
                        .eq(EduFormEnroll::getFormRefName, "edu_enrollmen_brochure")
                        .ne(
                                !ObjectUtils.isEmpty(vo.getFormId()),
                                EduFormEnroll::getFormId,
                                vo.getFormId());

                long count = eduFormEnrollService.count(formQueryWrapper);
                if (count > 0) {
                    throw new AppException("当前学校已存在招生类别，请输入其他招生类别");
                }
                QueryWrapper<EduFormEnroll> form2QueryWrapper = new QueryWrapper<>();
                form2QueryWrapper
                        .lambda()
                        .eq(EduFormEnroll::getSchoolId, orgId)
                        .eq(EduFormEnroll::getOrderNo, vo.getOrderNo())
                        .eq(EduFormEnroll::getFormRefId, vo.getFormRefId())
                        .eq(EduFormEnroll::getFormRefName, "edu_enrollmen_brochure")
                        .ne(
                                !ObjectUtils.isEmpty(vo.getFormId()),
                                EduFormEnroll::getFormId,
                                vo.getFormId());

                long count2 = eduFormEnrollService.count(form2QueryWrapper);
                if (count2 > 0) {
                    throw new AppException("当前学校已存在排序号，请输入其他排序号");
                }


                long count3 = eduFormEnrollService.count(form2QueryWrapper);
                if (count3 > 0) {
                    throw new AppException("已存在申报数据，不允许修改");
                }

                form.setFormClass(vo.getFormClass());
                form.setConfigName(vo.getConfigName());
                form.setOrderNo(vo.getOrderNo());
                eduFormEnrollService.saveOrUpdate(form);
            }
        } else {
            throw new AppException("获取不到表单类型");
        }
        //将主键设置回vo使操作日志可以取到
        vo.setFormId(form.getFormId());
        clearCache(form.getFormId());
        clearCacheSchool(form.getSchoolId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduFormEnroll0005", title = "报名表单管理修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduFormEnroll0005",
            operationName = "报名表单管理修改",
            dataType = "formId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduFormEnrollVO edit(EduFormEnrollVO vo) {
        if (ObjectUtils.isEmpty(vo.getFormId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduFormEnroll oldEntity = eduFormEnrollService.getById(vo.getFormId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        if (ObjectUtils.isEmpty(vo.getConfigName())){
            throw new AppException("招生类别不能为空");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduFormEnroll entity = Convert.convert(EduFormEnroll.class, vo);
        eduFormEnrollService.updateById(entity);
        clearCache(entity.getFormId());
        clearCacheSchool(entity.getSchoolId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduFormEnroll0006", title = "报名表单管理根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduFormEnroll0006",
            operationName = "报名表单管理删除",
            dataType = "formId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduFormEnrollKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getFormId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduFormEnroll entity = eduFormEnrollService.getById(vo.getFormId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduFormEnrollService.removeById(vo.getFormId());
        clearCache(entity.getFormId());
        clearCacheSchool(entity.getSchoolId());
    }

    @Override
    @OpApi(funcCode = "eduFormEnroll0007", title = "根据表单id获取表单字段配置信息", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    @Cached(name = EduCache.EDU_ENROLL_FORM_PARAMS, key = "#vo.formId", cacheType = CacheType.BOTH, expire = 86400, localExpire = 20)
    public List<EduFormEnrollParamsVO> getParamsListByFormId(EduFormEnrollKeyVO vo) {
        if(StringUtils.isBlank(vo.getFormId())){
            throw new AppException("表单id不能为空");
        }
        LambdaQueryWrapper<EduFormEnrollParams> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EduFormEnrollParams::getFormId,vo.getFormId())
                .orderByDesc(EduFormEnrollParams::getOrderNo);
        List<EduFormEnrollParams> list=eduFormEnrollParamsService.list(queryWrapper);
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        List<EduFormEnrollParamsVO> resList =
                Convert.toList(
                        EduFormEnrollParamsVO.class, list);
        dictHelper.valueToName(resList, Arrays.asList(EduFormEnrollParamsDictEnum.values()));
        return resList;
    }

    @Override
    @OpApi(funcCode = "eduFormEnroll0008", title = "报名表单管理根据学校id获取表单配置信息", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    @Cached(name = EduCache.EDU_ENROLL_FORM_SCHOOL, key = "#vo.schoolId", cacheType = CacheType.BOTH, expire = 86400, localExpire = 20)
    public List<EduFormEnrollVO> getFormListBySchoolId(EduFormEnrollSchoolVO vo) {
        if(StringUtils.isBlank(vo.getSchoolId())){
            throw new AppException("所属学校不能为空");
        }
        if(StringUtils.isBlank(vo.getFormType())){
            throw new AppException("表单大类不能为空");
        }
        if(vo.getYear()==null){
            vo.setYear(eduHelper.thisYear());
        }
        LambdaQueryWrapper<EduFormEnroll> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EduFormEnroll::getYear,vo.getYear())
                .eq(EduFormEnroll::getSchoolId,vo.getSchoolId())
                .eq(EduFormEnroll::getFormType,vo.getFormType())
                .eq(EduFormEnroll::getStatus, "on");
        List<EduFormEnroll> list=eduFormEnrollService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        List<EduFormEnrollVO> retVO=Convert.toList(EduFormEnrollVO.class,list);
        return retVO;
    }

    @Override
    @OpApi(funcCode = "eduFormEnroll0009", title = "报名表单管理保存义务教育固定表单信息", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduFormEnroll0009",
            operationName = "报名表单管理保存义务教育固定表单信息",
            dataType = "formConfigId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void saveYwFixedFormInfo(FormSaveVO vo) {
        if(ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(eduHelper.thisYear());
        }
        String schoolId = vo.getSchoolId();
        Assert.hasText(schoolId, "学校id不能为空");
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        QueryWrapper<EduFormEnroll> checkQueryWrapper = new QueryWrapper<>();
        checkQueryWrapper
                .lambda()
                .eq(EduFormEnroll::getSchoolId, schoolId)
                .eq(EduFormEnroll::getYear,vo.getYear())
                .in(EduFormEnroll::getOrderNo, Arrays.asList(1, 2, 3, 4, 6));
        List<EduFormEnroll> checkList = eduFormEnrollService.list(checkQueryWrapper);
        QueryWrapper<EduAppointSchool> appointSchoolQueryWrapper = new QueryWrapper<>();
        appointSchoolQueryWrapper.lambda().eq(EduAppointSchool::getNewSchoolId, schoolId)
                .eq(EduAppointSchool::getStatus,BoolEnum.TRUE.getType());
        long cqe=eduAppointSchoolService.count(appointSchoolQueryWrapper);
        if (checkList.size() >= 4) {
            List<String> idList =
                    checkList.stream()
                            .filter(item -> item.getOrderNo() == 6)
                            .map(EduFormEnroll::getFormId)
                            .collect(Collectors.toList());

            if ( cqe> 0
                    && idList.size() <= 0) {
                saveFixedForm("E类", "E", 6, vo);
            } else if (cqe <= 0
                    && idList.size() > 0) {
                eduFormEnrollService.removeByIds(idList);
            }
            return;
        }
        if (cqe>0){
            saveFixedForm("E类", "E", 6, vo);
        }
        saveFixedForm("A类", "A", 1, vo);
        saveFixedForm("B类", "B", 2, vo);
        saveFixedForm("C类", "C", 3, vo);
        saveFixedForm("特殊户口类", "特殊户口", 4, vo);
        clearCacheSchool(vo.getSchoolId());
    }

    void saveFixedForm(String formName, String configName, Integer orderNo, FormSaveVO vo) {
        EduFormEnroll formSave = new EduFormEnroll();
        formSave.setFormId(IdUtil.simpleUUID());
        formSave.setOrderNo(orderNo);
        formSave.setConfigName(configName);
        formSave.setValidStatus(BoolEnum.TRUE.getType());
        formSave.setFormType(EduFormTypeEnum.YWENROLL.getType());
        formSave.setFormName(formName);
        formSave.setSchoolId(vo.getSchoolId());
        formSave.setFormRefName(vo.getFormRefName());
        formSave.setFormRefId(vo.getFormRefId());
        formSave.setStatus(ArticleStatusEnum.draft.getType());
        formSave.setYear(vo.getYear());
        formSave.setAreaCode(vo.getAreaCode());
        eduFormEnrollService.save(formSave);
    }


    private void clearCache(String formId){
        if (StringUtils.isNotBlank(formId)) {
            Cache cache = JetCacheUtils.create(EduCache.EDU_ENROLL_FORM_PARAMS, CacheType.BOTH);
            if (cache != null) {
                cache.remove(formId);
            }
        }
    }
    private void clearCacheSchool(String schoolId){
        if (StringUtils.isNotBlank(schoolId)) {
            Cache cache = JetCacheUtils.create(EduCache.EDU_ENROLL_FORM_SCHOOL, CacheType.BOTH);
            if (cache != null) {
                cache.remove(schoolId);
            }
        }
    }
    @Override
    @OpApi(funcCode = "eduFormEnroll0012", title = "报名表单管理动态表单字段配置保存", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduFormEnroll0012",
            operationName = "报名表单管理动态表单字段配置保存",
            dataType = "formConfigId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void saveFormEnrollParams(SaveFormEnrollParamsVO vo) {
        String formId = vo.getFormId();
        if(StringUtils.isBlank(formId)){
            throw new AppException("表单id不能为空");
        }
        EduFormEnroll eduFormEnroll=eduFormEnrollService.getById(formId);
        if(eduFormEnroll==null){
            throw new AppException("表单信息不存在，请先刷新页面后重试");
        }

        //学校在有报名数据的情况下不允许新增修改删除字段，管理员可以新增修改删除
        EduSchool school = eduSchoolService.getById(SessionUtil.getOrgId());
        if(school!=null){
            EduFormEnrollVO eduFormEnrollVO = Convert.convert(EduFormEnrollVO.class, eduFormEnroll);
            checkSave(eduFormEnrollVO);
        }


        QueryWrapper<EduFormEnrollParams> deleteQueryWrapper = new QueryWrapper<>();
        deleteQueryWrapper
                .lambda()
                .eq(EduFormEnrollParams::getFormId, formId)
                .eq(EduFormEnrollParams::getFixedFlag, BoolEnum.FALSE.getType());
        eduFormEnrollParamsService.remove(deleteQueryWrapper);
        if(!CollectionUtils.isEmpty(vo.getList())){
            List<EduFormEnrollParamsVO> saveList =
                    vo.getList().stream()
                            .filter(item -> BoolEnum.FALSE.getType().equals(item.getFixedFlag()))
                            .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(saveList)) {
                List<EduFormEnrollParams> paramsList =new ArrayList<>();
                int i=0;
                for (EduFormEnrollParamsVO eduFormEnrollParamsVO:saveList) {
                    i=i+1;
                    EduFormEnrollParams params=Convert.convert(EduFormEnrollParams.class,eduFormEnrollParamsVO);
                    params.setFormConfigId(IdUtil.simpleUUID());
                    params.setFormId(formId);
                    params.setOrderNo(i + 30);
                    params.setParam("param"+i);
                    paramsList.add(params);
                }
                eduFormEnrollParamsService.saveBatch(paramsList);
            }
        }
        clearCache(vo.getFormId());
        clearCacheSchool(eduFormEnroll.getSchoolId());

    }

    @Override
    @OpApi(
            funcCode = "eduFormEnroll0015",
            title = "报名表单管理获取报名字段模板",
            funcType = FuncTypeEnum.query,
            checkPrivilege = BoolEnum.FALSE,
            savelog = false)
    public TreeRetVO getFormEmrollPramTreeList(OrgTreeVO orgTreeVO) {
        String searchText = orgTreeVO.getSearchText();
        List<EduFormEnrollVO> sysOrgList = new ArrayList<>();
        boolean lazy = false;
        if (orgTreeVO.getLazy() != null) {
            lazy = orgTreeVO.getLazy();
        }

        String schoolId = SessionUtil.getSessionInfo().getOrgId();
        Integer year = eduHelper.thisYear();
        if (lazy) {
            String parentId = orgTreeVO.getParentKey();
            if (StringUtils.isBlank(parentId)) {
                parentId = "#";
            }
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("year",year);
            queryMap.put("parentId", parentId);
            queryMap.put("schoolId", schoolId);

            sysOrgList = eduFormEnrollService.selectEnrollParamListLazy(queryMap);
        }else {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("year",year);
            queryMap.put("schoolId", schoolId);
            sysOrgList = eduFormEnrollService.selectEnrollParamList(queryMap);
        }

        TreeRetVO treeRetVO = new TreeRetVO();
        if (CollectionUtils.isEmpty(sysOrgList)) {
            treeRetVO.setTreeList(new ArrayList<>());
            return treeRetVO;
        }
        List<TreeVO> antTreeVOS = new ArrayList<>();
        for (EduFormEnrollVO sysOrg : sysOrgList) {
            TreeVO antTreeVO = new TreeVO();
            antTreeVO.setKey(sysOrg.getFormId());
            antTreeVO.setParentKey(sysOrg.getParentId());
            if ("1".equalsIgnoreCase(sysOrg.getFormType())) {
                if (StringUtils.isNotBlank(sysOrg.getConfigType())) {
                    String configTypeName = dictHelper.getValue("SCHOOLCONFIGTYPE", sysOrg.getConfigType());
                    antTreeVO.setTitle(configTypeName + "-" + sysOrg.getFormName());
                } else {
                    antTreeVO.setTitle(sysOrg.getFormName());
                }

            } else {
                antTreeVO.setTitle(sysOrg.getFormName());
            }

            if (StringUtils.isNotBlank(searchText)) {
                antTreeVO.setLoaded(true);
                antTreeVO.setExpanded(true);
            } else {
                antTreeVO.setLoaded(false);
                antTreeVO.setExpanded(false);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("title", "title");
            antTreeVO.setScopedSlots(map);
            antTreeVOS.add(antTreeVO);
        }
        if (lazy) {
            treeRetVO.setTreeList(antTreeVOS);
            return treeRetVO;
        }
        treeRetVO.setTreeList(TreeUtil.constructTaskDTOToTree(antTreeVOS));
        return treeRetVO;
    }

}
